package com.controller.experiment;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@Controller
@RequestMapping("/model")
public class TeacherController {
    private List<Teacher> db=new ArrayList();
    {
        System.out.println("初始化db属性，模拟数据库");
        db.add(new Teacher(1,"zk",new Date()));
        db.add(new Teacher(2,"zrs",new Date()));
        db.add(new Teacher(3,"hxy",new Date()));
        db.add(new Teacher(4,"hkj",new Date()));
    }
    @GetMapping("/teacher/{id}")
    @ResponseBody
    public Map<String,Object> findTeacherById(@PathVariable("id") Integer id){
        HashMap<String,Object> map=new HashMap<>();
        map.put("code",1003);
        map.put("msg","该工号对应的教师不存在");
        map.put("data",null);
        System.out.println("查询信息"+id);
        for (Teacher t:db){
            if (t.getId().equals(id)){
                map.put("code",1000);
                map.put("msg","查询成功");
                map.put("data",t);
            }
        }
        return map;

    }

    @GetMapping("/teacher/all")
    @ResponseBody
    public Map<String,Object>  findAllTeacher(){
        System.out.println("查询所有信息");
        HashMap<String,Object> map=new HashMap<>();
        map.put("code",1000);
        map.put("msg","查询所有信息成功");
        map.put("data",db);
        return map;
    }

    @RequestMapping(method = RequestMethod.POST,value = "/teacher")
    @ResponseBody
    public Map addTeacher(@RequestBody Teacher t){
        System.out.println("添加信息"+t);
        db.add(t);
        HashMap<Object,Object> map=new HashMap<>();
        map.put("code",1000);
        map.put("msg","添加信息成功");
        map.put("data",t);
        System.out.println(db);
        return map;
    }
    @RequestMapping(method = RequestMethod.PUT, value= "/teacher")
    @ResponseBody
    public Map updateTeacher(@RequestBody Teacher t){
        System.out.println("修改信息"+t);
        db.remove(t);
        HashMap<Object,Object> map=new HashMap<>();
        map.put("code",1000);
        map.put("msg","修改信息成功");
        map.put("data",null);
        System.out.println(db);
        return map;
    }
    @RequestMapping(method = RequestMethod.DELETE,value = "/teacher/{id}")
    @ResponseBody
    public HashMap<String,Object> deleteTeacherById(@PathVariable("id") Integer id){
        System.out.println("删除信息"+id);
        for (int i = 0; i < db.size(); i++) {
            if(db.get(i).getId()==id.intValue()){
                db.remove(i);
            }
        }
        HashMap<String,Object> map=new HashMap<>();
        map.put("code",1000);
        map.put("msg","删除成功");
        map.put("data",null);
        System.out.println(db);
        return map;
    }
}

